from werkzeug.security import generate_password_hash, check_password_hash
from app.models import User
from app.extensions import db

class AuthService:
    """用户认证服务"""

    @staticmethod
    def register(username: str, password: str, role: str = '家长') -> dict:
        """用户注册逻辑"""
        if User.query.filter_by(username=username).first():
            return {'code': 400, 'message': '用户名已存在'}
        
        new_user = User(
            username=username,
            password=generate_password_hash(password),
            role=role
        )
        db.session.add(new_user)
        db.session.commit()
        return {'code': 201, 'message': '注册成功', 'user_id': new_user.user_id}

    @staticmethod
    def login(username: str, password: str) -> dict:
        # 打印加密后的密码
        print(generate_password_hash(password))
        """用户登录验证"""
        user = User.query.filter_by(username=username).first()
        if not user or not check_password_hash(user.password, password):
            return {'code': 401, 'message': '用户名或密码错误'}
        return {'code': 200, 'message': '登录成功', 'user': user.to_dict()}

    @staticmethod
    def reset_password(user_id: int, new_password: str) -> dict:
        """密码重置"""
        user = User.query.get(user_id)
        if not user:
            return {'code': 404, 'msg': '用户不存在'}
        user.password = generate_password_hash(new_password)
        db.session.commit()
        return {'code': 200, 'msg': '密码已更新'}